package net.kesumu.yushabu;

import java.net.URI;
import java.net.URLEncoder;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.BackgroundUtil;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;

import com.codebutler.android_websockets.WebSocketClient;
import com.umeng.message.PushAgent;

import net.kesumu.yushabu.R;
import net.kesumu.yushabu.R.id;
import net.kesumu.yushabu.R.layout;
import net.kesumu.yushabu.R.menu;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
import android.os.Build;

public class FriendRequestActivity extends Activity {
    
    private EasyStorage mEasyStorage;

    String mMyId;
    String mFriendId;
    
    String mFriendRequestMessage;
    TextView mFriendRequestMessageView;
    
    TextView mTextMessageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_request);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_friend_request));
      //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));

        
        
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyId = mEasyStorage.getString("mMyId");
        
        Intent receiveIntent = getIntent();
//        mMyId = receiveIntent.getStringExtra("myId");
        mFriendId = receiveIntent.getStringExtra("friendId");
        
        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }
    
    @Override
    protected void onStart() {
        
        mFriendRequestMessageView = (TextView) findViewById(R.id.friendRequestMessage);
        
        mTextMessageView = mFriendRequestMessageView;
        mTextMessageView.requestFocus(MODE_APPEND);
        mTextMessageView.setImeActionLabel(getResources().getString(R.string.btn_send), 
                                                            KeyEvent.KEYCODE_ENTER);
        mTextMessageView.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    friendRequest(findViewById(R.id.btn_friendRequest));
                    handled = true;
                }
                return handled;
            }
        });
        
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.friend_request, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }
    
    public void friendRequest(View clickedView) {
        mFriendRequestMessage = mFriendRequestMessageView.getText().toString();
        sendRequest(jsonUtil.getFriendRequestJSON(mMyId, mFriendId, mFriendRequestMessage));
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_friend_request,
                    container, false);
            return rootView;
        }
    }

    
    @Override
    protected void onDestroy() {
        super.onDestroy();
         
        if(client != null & client.isConnected()){
            client.disconnect();
        }
    }
    
    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {
                
            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    //remove the null judge for immediately send a message after connection setup
    private void sendRequest(String message) {
        client.send(message);
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_FRIEND_REQUEST_SOURCE)) {
                String result = jObj.getString("result");
                showToast(result); 
                
                //go back to the previous activity
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                   }
                });
            }
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }
}
